/**
 * Created by yinhong on 2018/7/7.
 */

//获取Id
//var searchURL=window.location.search;
var searchURL="?id=37072541600000_20180426235654&role=1";
searchURL = searchURL.substring(1, searchURL.length);
var targetPageId = searchURL.split("&");
var searchDataMap={};
for(var i=0;i<targetPageId.length;i++) {
    searchDataMap[targetPageId[i].split("=")[0]] = targetPageId[i].split("=")[1]
};
// var weatherIcon = [{"雷阵雨":'6'},{"晴天":'1'},{"晴夜":'2'},{"多云（白天）":'3'},{"多云（夜晚）":'4'},{"阴":'5'},{"雪":'7'},{"风":'8'},{"雾霾沙尘":'9'}];

//


var data24h = [];
var dataweek = [];

//--------数据初始化------------
//当前实况
function weatherConditionsTop(json,container){
    if(!json){
        return;
    };
    if(json.status==200){
        var htmlStr="";
        var dataMap=json.data;
        //加载图片
        if(dataMap.weatherIcon){
            htmlStr+='<div class="weatherIcon_weatherConditions">'+
                '<img src="'+dataMap.weatherIcon+'" alt="">'+
                '</div>';
        };
        //拼接温度
        if(dataMap.temperature){
            htmlStr+='<div class="temperature_weatherConditions">'+
                '<span class="num_weatherConditions">'+dataMap.temperature+'</span>'+
                '<span class="num_temp">°C</span>'+
                '<span class="num_time">'+dataMap.datetime.substring(11,16)+'发布</span>'+
                '</div>';
        };
        htmlStr+='<div class="details_weatherConditions">';
        //拼接气压
//      if(dataMap.pressure){
//          htmlStr+='<div class="item_weatherConditions">'+
//              '<img class="pressure_weatherConditions" src="./../images/icon/pressure.png" alt="">'+
//              '<ul class="ul_weatherConditions">'+
//              '<li>气压</li>'+
//              '<li>'+dataMap.pressure+'Mpa</li>'+
//              '</ul>'+
//              '<span class="line_weatherConditions"></span>'+
//              '</div>'
//      };
        //拼接wind
        if(dataMap.windDirection){
            htmlStr+='<div class="item_weatherConditions">'+
                '<img class="pressure_weatherConditions" src="./../images/icon/wind.png" alt="">'+
                '<ul class="ul_weatherConditions">'+
                '<li>风向 '+dataMap.windDirection+'</li>'+
                '<li>风力 '+dataMap.windSpeed+'m/s</li>'+
                '</ul>'+
                '<span class="line_weatherConditions"></span>'+
                '</div>'
        };
        //拼接湿度
        if(dataMap.humidity){
            htmlStr+='<div class="item_weatherConditions">'+
                '<img class="pressure_weatherConditions" src="./../images/icon/humidity.png" alt="">'+
                '<ul class="ul_weatherConditions">'+
                '<li>相对湿度</li>'+
                '<li>'+dataMap.humidity+'%</li>'+
                '</ul>'+
                '<span class="line_weatherConditions"></span>'+
                '</div>'
        }
        htmlStr+='</div><div class="description_weatherConditions">未来2小时的总降水量</div>';
        container.append(htmlStr);
    };

};
$.ajax({
    "url":"http://test.yulaile.cc/bootspr/weatherdata/nowData",
    type:'GET', //POST
    async:true,    //或false,是否异步
    data:{

    },
    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
    success:function(data){
    	console.log(data);
        weatherConditionsTop(data,$('#wrapper_weatherConditions'));
    }
});

//未来两小时降雨
$.ajax({
    type:"get",
    url:"https://api.caiyunapp.com/v2/HRxgfKljkFJ=TVCF/117.15,37.32/forecast.jsonp",
    dataType:"jsonp",
    success:function(data){
        console.log(data.result.minutely);//未来120分钟降水，取description和precipitation_2h（取整10分钟的，显示12个点）
//					CLEAR_DAY：晴天
//					CLEAR_NIGHT：晴夜
//					PARTLY_CLOUDY_DAY：多云
//					PARTLY_CLOUDY_NIGHT：多云
//					CLOUDY：阴
//					RAIN： 雨
//					SNOW：雪
//					WIND：风
//					HAZE：雾霾沙尘
        //图片和skycon对应上就行了，匹配展示对应的图片
        console.log(data.result.hourly);//未来48小时逐小时天气预报，取温度temperature，天气现象描述skycon，
        var rander2h = data.result.minutely;
        if(rander2h.status == 'ok'){
            $('.forecastCharts h5').empty().html(rander2h.description);
            var dataArry = ['0'];
            var dataY2h = rander2h.precipitation_2h;
            $.each(dataY2h,function (i,ele) {
                if(i>0&&i%10 == "0"){
                   // console.log(i,ele);
                    dataArry.push(ele);
                }
            });
            dataArry.push(dataY2h[dataY2h.length-1]);
            // console.log(dataArry);
            getCharts2h(dataArry);
        }

        var forecast24h = data.result.hourly;



    }
});


//未来24小时 逐3小时
$.ajax({
    url:"http://test.yulaile.cc/bootspr/weatherdata/forecast",
    type:'GET', //POST
    async:true,    //或false,是否异步
    data:{

    },
    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
    success:function(data){
        data24h = data.WeatherData[0].hourly_forecast;
        dataweek = data.WeatherData[0].daily_forecast;
        suggest=data.WeatherData[0].suggestion;
        console.log(data24h)
        console.log(dataweek)
        console.log(suggest)
        //未来24小时 逐3小时预报 和 未来一周天气预报
        getHours(data24h,'hourWrap');
        forecstHtml(dataweek,'weekList');
		getSuggest(suggest,'suggests');

    },
    error: function(e){
        console.log(e);
    }
});
var liWidth = 2.5; //24小时 每个模块的宽度 2.2rem


//---------函数封装------------

//未来2小时 降水量 charts图表
function getCharts2h(dataY){
    var myCharts = echarts.init(document.getElementById('chartsWrap'));

    var option = {
        grid:{
            top:0,
            bottom:50
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            axisLine: {
                lineStyle: {
                    color: '#fff'
                }
            },
            axisTick: {
                lineStyle: {
                    color: '#fff'
                }
            },
            nameTextStyle: {
                color: '#fff'
            },
            data : ['0','10','20','30','40','50','60','70','80','90','100','110','120']
        },
        yAxis: {
            type: 'value',
            splitNumber: 3,
            min:0,
            axisLine: {
                show:false,
                lineStyle: {
                    color: '#fff'
                }
            },
            axisTick: {
                show:false,
                lineStyle: {
                    color: '#fff'
                }
            },
            splitLine: {
                show:false,
                lineStyle: {
                    color: "#409dcc"
                }
            },
            axisLabel:{
            	show:false,
                formatter: function (value) {
                   var texts = [];
                   if (value <=0.25) {
                       texts.push('小雨');
                   }else if (value <=0.35) {
                       texts.push('中雨');
                   }else if (value > 0.35){
                       texts.push('大雨');
                   }
                   return texts;
              
               }
            }
        },
        series: [{
            type: 'line',
            smooth:true,
            symbol: 'none',
            itemStyle: {color: '#4377b1'},
            areaStyle: {color: '#4377b1'},
            // data: ['0','0.1','0.2','0.3','0.32','0.05','0.3','0.4','0.25','0.46','0.2','0.1','0.12']
            data: dataY
        }]
    };

    myCharts.setOption(option);
}

//未来24小时逐3小时预报  html
function getHours(arry,wrapId){
    var str = '';
    $.each(arry,function(i,ele){
        str = '<li class="list">' +
                '<p class="time">'+ele.date.slice(10)+'</p>'+
                // '<p class="weatherIcon"><img src="" alt="">'+ele.cond.txt+'</p>'+
                '<p class="weatherIcon">'+ele.cond.txt+'</p>'+
                '<p class="temperature">'+ele.tmp+'℃</p>'+
                '<p class="temperature">'+ele.wind.dir+'</p>'+
                '<p class="temperature">'+ele.wind.sc+'级</p>'+
        '</li>';
        $('#'+wrapId).append(str);
    });
    $('#'+wrapId).css('width',arry.length*liWidth+'rem');
}
//意见建议  html
function getSuggest(arry,wrapId){
    var str = '';
    str = '<li>'+arry.air.txt+'</li>'+
    		  '<li>'+arry.comf.txt+'</li>'+
    		  '<li>'+arry.cw.txt+'</li>'+
    		  '<li>'+arry.drsg.txt+'</li>'+
    		  '<li>'+arry.flu.txt+'</li>'+
    		  '<li>'+arry.sport.txt+'</li>'+
    		  '<li>'+arry.trav.txt+'</li>'+
          '<li>'+arry.uv.txt+'</li>';
    $('.'+wrapId).append(str);
}
//未来一周天气预报 html
function forecstHtml(arry,wrapId){
    var str = '';
    $('#'+wrapId).empty();
    $.each(arry,function(i,ele){
        str = '<li class="list">' +
            '<div class="listTitle">'+
                '<div class="listIcon">'+
                    '<img src="" alt="">'+
                '</div>'+
                '<div class="listTime">'+
                    '<p>'+ele.date+'</p>'+
                    '<p>白天:'+ele.cond.txt_d+'</p>'+
                '</div>'+
                '<div class="listTemp">'+
                    '<p>'+ele.tmp.min+'℃-'+ele.tmp.max+'℃</p>'+
                    '<p>晚上:'+ele.cond.txt_n+'</p>'+
                '</div>'+
//              '<div class="listShidu">'+
//                   '<p>'+Number(ele.pcpn).toFixed(0)+'%</p>'+
//              '</div>'+
                '<div class="listUp">'+
                     '<span>></span>'+
                '</div>'+
            '</div>'+
            '<div class="listBody">'+
                '<p>相对湿度：'+Number(ele.hum).toFixed(0)+'%</p>'+
                '<p>风力风向：'+ele.wind.sc+'级&nbsp;&nbsp;'+ele.wind.dir+'</p>'+
//              '<p>降水量：'+ele.pcpn+'mm&nbsp;&nbsp;降水概率：'+ele.pop+'%</p>'+
                '<p>日出时间：'+ele.astro.sr+'&nbsp;日落时间：'+ele.astro.ss+'</p>'+
                '<p>紫外线指数：'+ele.uv+'级</p>'+
            '</div>'+
            '</li>';
        
        $('#'+wrapId).append(str);
    });
   	 	$('#weekList .list:first-child').trigger('click');
}


//---------事件-----------
$('#weekList').on('click','.list',function () {
//    $(this).addClass('listActive');
    if( $(this).attr('checkOff') == 'true'){
        $(this).attr('checkOff','false');
        $(this).find('.listUp').find('span').html('>').css("transform","rotate(0deg)");
        $(this).find('.listBody').slideUp();
    }else{
        $(this).attr('checkOff','true');
        $(this).siblings().attr('checkOff','false').find('.listUp').find('span').html('>').css("transform","rotate(0deg)");
        $(this).siblings().find('.listBody').slideUp();
        $(this).find('.listUp').find('span').html('>').css("transform","rotate(90deg)");
        $(this).find('.listBody').slideDown();
    }
});



